#!/bin/bash

#cd "$(dirname "$0")"是为了进入到脚本所在目录下 
source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/./common.sh"

#获取popins
function download_popins() {
  echo "# popins与seqan正在下载"
  wget -t 40 -c -P $1 https://github.com/bkehr/popins/archive/refs/tags/1.0.1.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# popins已经克隆成功\033[0m"
  else
    echo -e "\033[31m# popins下载失败,请重新执行脚本\033[0m"
    exit 
  fi
  wget -t 40 -c -P $1 https://github.com/seqan/seqan/archive/refs/tags/seqan-v2.4.0.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# seqan已经克隆成功\033[0m"
  else
    echo -e "\033[31m# seqan下载失败,请重新执行脚本\033[0m"
    exit 
  fi
  tar xf $1/1.0.1.tar.gz -C $1
  tar xf $1/seqan-v2.4.0.tar.gz -C $1
  mv $1/popins-1.0.1 $1/popins
  mv $1/seqan-seqan-v2.4.0 $1/seqan
  cd "$1"/seqan
  sed -i -e 's/8u + numSamples/7u + numSamples/g' include/seqan/vcf_io/read_vcf.h
  cd "$1"/popins
  mv ../seqan/include/seqan/ seqan
}

function install_popins() {
  cd "$1"/popins 
  unset INCLUDE
  sed -i -e 's/-63//g' popins.config
  sed -i -e 's/g++/clang++/;s/MM popins.cpp/MM popins.cpp -isystem ./' Makefile
  sed -i "14s/$/ -march=armv8.2-a -fsigned-char -ffp-contract=off/" Makefile
  sed -i "21s/$/ -march=armv8.2-a -fsigned-char -ffp-contract=off/" Makefile
  make -j $(nproc)
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# popins编译成功\033[0m"
  else
    echo -e "\033[31m# popins编译失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function cp_popins() {
  mkdir -p "$2"/popins
  cp -r "$1"/popins/* "$2"/popins
}

# 创建modulefiles文件
function write_popins_module() {
  cat >"$1/popins/popins_modulefiles"<<EOF
#%Module1.0
conflict popins
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
prepend-path PATH \$pwd
EOF
}

function main() {
  rm -rf "$1"/*
  is_equal_build_install_path "$1" "$2"
  download_popins "$1"
  install_popins "$1"
  cp_popins "$1" "$2"
  write_popins_module "$2"
  rm -rf "$1"/popins
}

main "$@"
